package com.huluspace.jpahibernate.service;

import com.huluspace.jpahibernate.dto.LoginResponse;
import com.huluspace.jpahibernate.dto.UserDTO;
import com.huluspace.jpahibernate.model.User;
import com.huluspace.jpahibernate.repository.UserRepository;
import com.huluspace.jpahibernate.security.JwtUtil;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserService {
  private final UserRepository userRepository;
  private final PasswordEncoder passwordEncoder;
  private final JwtUtil jwtUtil;
  public UserService(UserRepository userRepository, PasswordEncoder passwordEncoder, JwtUtil jwtUtil) {
    this.userRepository = userRepository;
    this.passwordEncoder = passwordEncoder;
    this.jwtUtil = jwtUtil;
  }

  // 用户注册业务
  public String register(User user) {
    if (userRepository.findByUsername(user.getUsername()).isPresent()) {
      return "用户名已存在";
    }
    user.setPassword(passwordEncoder.encode(user.getPassword()));
    user.setEnabled(true);
    userRepository.save(user);
    return "注册成功";
  }

  // 基于用户名、密码登录，若成功返回带JWT令牌的登录响应
  public LoginResponse login(String username, String password) {
    return userRepository.findByUsername(username)
        .filter(u -> passwordEncoder.matches(password, u.getPassword()))
        .map(u -> {
          return new LoginResponse(jwtUtil.generateToken(u.getUsername()));
        })
        .orElseThrow(() -> new RuntimeException("用户名或密码错误"));
  }

  // 列出所有用户
  public List<UserDTO> listAllUsers() {
    List<User> users = userRepository.findAll();
    return users.stream()
        .map(user -> new UserDTO(user.getId(), user.getUsername()))
        .toList();
  }

}
